<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width, viewport-fit=cover" />
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<title>高德地图 - 搜索</title>
		<script src="https://cdn.tailwindcss.com"></script>
		<link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
		<style type="text/tailwindcss">
			@layer utilities {
				.search-shadow {
					box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
				}
				.suggestion-item-hover {
					@apply bg-gray-100 transition-colors duration-200;
				}
				.safe-area-top {
					padding-top: env(safe-area-inset-top);
				}
				.safe-area-bottom {
					padding-bottom: env(safe-area-inset-bottom);
				}
			}
		</style>
		<style>
			html,
			body {
				width: 100%;
				height: 100%;
				padding: 0;
				margin: 0;
				touch-action: manipulation;
			}

			#container {
				width: 100%;
				height: 100%;
			}

			.zuiss {
				width: 375px;
				position: fixed;
				left: 50%;
				transform: translateX(-50%);
				top: 20px;
				z-index: 99999;
			}

			#suggestion-container {
				max-height: 60vh;
				overflow-y: auto;
				z-index: 2000;
			}

			.suggestion-item {
				cursor: pointer;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				padding: 12px 16px;
			}

			.custom-marker {
				border: 2px solid #4285f4;
				background-color: white;
				border-radius: 50%;
				text-align: center;
				font-weight: bold;
				display: flex;
				align-items: center;
				justify-content: center;
				box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
			}

			::-webkit-scrollbar {
				width: 4px;
				height: 4px;
			}

			::-webkit-scrollbar-thumb {
				background-color: rgba(0, 0, 0, 0.2);
				border-radius: 2px;
			}

			.clear-btn {
				cursor: pointer;
				transition: opacity 0.2s;
			}

			.clear-btn:hover {
				opacity: 0.7;
			}

			.positionDwn {
				width: 50px;
				height: 50px;
				background: #FFFFFF;
				border-radius: 10px;
				position: absolute;
				bottom: 30%;
				right: 10px;
				display: flex;
				align-items: center;
				justify-content: center;
				z-index: 9999;
			}

			.positionDwn img {
				width: 30px;
				height: 30px;
			}
			.btnButom{
				width: 370px;
				height: 40px;
				background: #4285f4;
				color: #FFFFFF;
				border-radius: 10px;
				text-align: center;
				line-height: 40px;
				position: fixed;
				bottom: 40px;
				left: 50%;
				transform: translateX(-50%);
				font-size: 20px;
				letter-spacing: 4px;
			}
		</style>
	</head>
	<body>
		<div class="zuiss">
			<div class="flex search-shadow rounded-lg overflow-hidden">
				<div class="flex-1 relative">
					<input type="text" id="search-input" placeholder="搜索地点、POI..."
						class="w-full px-5 py-4 pr-20 text-base focus:outline-none text-gray-800" autocapitalize="off"
						autocorrect="off">
					<i
						class="fa fa-search absolute right-12 top-1/2 transform -translate-y-1/2 text-gray-400 text-lg"></i>
					<!-- 清空按钮 -->
					<i id="clear-input"
						class="fa fa-times-circle clear-btn absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-400 text-lg hidden"></i>
					<!-- 搜索建议容器 -->
					<div id="suggestion-container"
						class="hidden absolute top-full left-0 right-0 bg-white rounded-b-lg border-t-0 border border-gray-200 mt-[-1px]">
						<div id="suggestion-list" class="p-1"></div>
					</div>
				</div>
				<button id="search-button"
					class="bg-blue-600 text-white px-6 py-4 hover:bg-blue-700 transition-colors duration-200">
					搜索
				</button>
			</div>
		</div>

		<div style="z-index: 999999;" id="result-panel"
			class="fixed bottom-0 left-0 right-0 bg-white rounded-t-xl shadow-lg p-4 z-1900 max-h-[60vh] overflow-y-auto transform translate-y-full transition-transform duration-300 ease-in-out safe-area-bottom">
			<div class="flex justify-between items-center mb-3">
				<h3 class="text-lg font-bold">搜索结果</h3>
				<button id="close-result" class="text-gray-500 hover:text-gray-700">
					<i class="fa fa-times text-xl"></i>
				</button>
			</div>
			<div id="result-list" class="space-y-2"></div>
		</div>

		<button style="z-index: 999999;" id="toggle-result"
			class="fixed bottom-6 right-6 bg-blue-600 text-white w-12 h-12 rounded-full shadow-lg flex items-center justify-center z-1800 hidden">
			<i class="fa fa-list"></i>
		</button>

		<div id="container"></div>

		<!-- <div class="positionDwn" onclick="myPlace">
			<img src="./image/icon2.png" alt="" />
		</div> -->
		
		<div class="btnButom" onclick="reportLocation">
			上报标记
		</div>

		<script type="text/javascript">
			window._AMapSecurityConfig = {
				securityJsCode: "1c5e88544f9343d57f171cda851f273f",
			};
		</script>
		<script src="https://webapi.amap.com/loader.js"></script>
		<script type="text/javascript" src='./js/citys.js'></script>
		<script type="text/javascript" src='./js/webview.js'></script>
		<script type="text/javascript">
			// 全局变量
			let map, autocomplete, placeSearch;
			let markers = []; // 存储搜索结果标记
			let hoverMarker = null; // 单独存储城市悬停标记
			let isResultVisible = false;
			let center = [116.397528, 39.920222];
			let option = this.getQueryVariable();
			let iconImg = './image/icon1.png'
			if (option.longitude) {
				center = [option.longitude, option.latitude]
			}

			AMapLoader.load({
					key: "1cba3a6567effb4d9d5083016ad9463f",
					version: "2.0",
				})
				.then((AMap) => {
					map = new AMap.Map('container', {
						zoom: 15,
						center: center,
						showIndoorMap: false,
						viewMode: '3D',
						resizeEnable: true,
						touchZoomCenter: 1,
					});

					hailiang()
					initSearch(AMap);
					addMyMarker(center[0], center[1]);

					window.addEventListener('resize', function() {
						map.resize();
					});
				})
				.catch((e) => {
					console.error(e);
				});

			function hailiang() {
				var style = [{
					url: 'https://webapi.amap.com/images/mass/mass0.png',
					anchor: new AMap.Pixel(6, 6),
					size: new AMap.Size(11, 11),
					zIndex: 3,
				}, {
					url: 'https://webapi.amap.com/images/mass/mass1.png',
					anchor: new AMap.Pixel(4, 4),
					size: new AMap.Size(7, 7),
					zIndex: 2,
				}, {
					url: 'https://webapi.amap.com/images/mass/mass2.png',
					anchor: new AMap.Pixel(3, 3),
					size: new AMap.Size(5, 5),
					zIndex: 1,
				}];

				var mass = new AMap.MassMarks(citys, {
					opacity: 0.8,
					zIndex: 111,
					cursor: 'pointer',
					style: {
						url: 'https://webapi.amap.com/images/mass/mass0.png',
						anchor: new AMap.Pixel(6, 6),
						size: new AMap.Size(11, 11),
						zIndex: 3,
					}
				});

				// 单独存储城市悬停标记，便于管理
				hoverMarker = new AMap.Marker({
					content: ' ',
					map: map
				});
				mass.on('mouseover', function(e) {
					hoverMarker.setPosition(e.data.lnglat);
					hoverMarker.setLabel({
						content: e.data.name
					})
				});
				mass.setMap(map);
			}
			// 将当前所在位置的图标放到地图上
			function addMyMarker(longitude, latitude) {
				//创建 AMap.Icon 实例：
				const icon = new AMap.Icon({
				  size: new AMap.Size(25, 34), //图标尺寸
				  image: "https://picsum.photos/100/100", //Icon 的图像
				  // imageOffset: new AMap.Pixel(-9, -3), //图像相对展示区域的偏移量，适于雪碧图等
				  imageSize: new AMap.Size(135, 40), //根据所设置的大小拉伸或压缩图片
				});
				// 将 Icon 实例添加到 marker 上:
				const viaMarker = new AMap.Marker({
				  position: new AMap.LngLat(longitude, latitude), //点标记的位置
				  // offset: new AMap.Pixel(-13, -30), //偏移量
				  icon: icon, //添加 Icon 实例
				  title: "北京",
				  zooms: [1, 18], //点标记显示的层级范围，超过范围不显示
				});
				map.add(viaMarker);
			}
			// 手动获取自己所在的位置
			function myPlace(){
				AMap.plugin('AMap.Geolocation', function() {
				  var geolocation = new AMap.Geolocation({
				    enableHighAccuracy: true, // 是否使用高精度定位，默认：true
				    timeout: 10000, // 设置定位超时时间，默认：无穷大
				    offset: [10, 20],  // 定位按钮的停靠位置的偏移量
				    zoomToAccuracy: true,  //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
				    position: 'RB' //  定位按钮的排放位置,  RB表示右下
				  })
				
				  geolocation.getCurrentPosition(function(status,result){
				        if(status=='complete'){
				            onComplete(result)
				        }else{
				            onError(result)
				        }
				  });
				
				  function onComplete (data) {
				    // data是具体的定位信息
				  }
				
				  function onError (data) {
				    // 定位出错
				  }
				})
			}
			
			// 上报标记位置
			function reportLocation(){
				
			}

			function initSearch(AMap) {
				AMap.plugin("AMap.AutoComplete", function() {
					autocomplete = new AMap.AutoComplete({
						input: "search-input",
						city: ""
					});

					AMap.plugin("AMap.PlaceSearch", function() {
						placeSearch = new AMap.PlaceSearch({
							pageSize: 10,
							pageIndex: 1,
							city: "",
							map: map,
							panel: "result-list",
							autoFitView: true
						});

						bindSearchEvents(AMap);
					});
				});
			}

			function bindSearchEvents(AMap) {
				const searchInput = document.getElementById('search-input');
				const searchButton = document.getElementById('search-button');
				const suggestionContainer = document.getElementById('suggestion-container');
				const suggestionList = document.getElementById('suggestion-list');
				const resultPanel = document.getElementById('result-panel');
				const toggleResultBtn = document.getElementById('toggle-result');
				const closeResultBtn = document.getElementById('close-result');
				const clearInputBtn = document.getElementById('clear-input');

				toggleResultBtn.addEventListener('click', toggleResultPanel);
				closeResultBtn.addEventListener('click', toggleResultPanel);

				// 清空按钮点击事件 - 确保清除所有标记
				clearInputBtn.addEventListener('click', function() {
					searchInput.value = '';
					clearInputBtn.classList.add('hidden');
					suggestionContainer.classList.add('hidden');
					clearAllMarkers(); // 清除所有标记
					document.getElementById('result-list').innerHTML = '';
					resultPanel.classList.add('translate-y-full');
					toggleResultBtn.classList.add('hidden');
					isResultVisible = false;

					// 清除PlaceSearch可能残留的标记
					if (placeSearch && placeSearch.clear) {
						placeSearch.clear();
					}
				});

				// 输入框内容变化时的处理
				searchInput.addEventListener('input', function() {
					const value = this.value.trim();

					if (value.length > 0) {
						clearInputBtn.classList.remove('hidden');
					} else {
						clearInputBtn.classList.add('hidden');
						suggestionContainer.classList.add('hidden');
						clearAllMarkers(); // 清除所有标记
						document.getElementById('result-list').innerHTML = '';
						resultPanel.classList.add('translate-y-full');
						toggleResultBtn.classList.add('hidden');
						isResultVisible = false;

						// 清除PlaceSearch可能残留的标记
						if (placeSearch && placeSearch.clear) {
							placeSearch.clear();
						}
					}
				});

				autocomplete.on("select", function(e) {
					searchByKeyword(e.poi.name);
					suggestionContainer.classList.add('hidden');
				});

				// 搜索建议处理
				searchInput.addEventListener('input', function() {
					const keyword = this.value.trim();
					if (keyword.length < 1) {
						suggestionContainer.classList.add('hidden');
						return;
					}

					autocomplete.search(keyword, function(status, result) {
						if (status === 'complete' && result.tips.length > 0) {
							suggestionContainer.classList.remove('hidden');
							suggestionList.innerHTML = '';
							result.tips.forEach(tip => {
								const item = document.createElement('div');
								item.className = 'suggestion-item suggestion-item-hover';
								item.innerHTML = `
									<div class="font-medium">${tip.name}</div>
									<div class="text-sm text-gray-500">${tip.district}${tip.address}</div>
								`;
								item.addEventListener('click', function() {
									searchInput.value = tip.name;
									clearInputBtn.classList.remove('hidden');
									searchByKeyword(tip.name);
									suggestionContainer.classList.add('hidden');
								});
								suggestionList.appendChild(item);
							});
						} else {
							suggestionContainer.classList.add('hidden');
						}
					});
				});

				// 搜索按钮点击事件
				searchButton.addEventListener('click', function() {
					const keyword = searchInput.value.trim();
					if (keyword) {
						searchByKeyword(keyword);
						suggestionContainer.classList.add('hidden');
					}
				});

				// 回车搜索
				searchInput.addEventListener('keypress', function(e) {
					if (e.key === 'Enter') {
						const keyword = this.value.trim();
						if (keyword) {
							searchByKeyword(keyword);
							suggestionContainer.classList.add('hidden');
						}
					}
				});

				// 点击页面其他地方隐藏建议列表
				document.addEventListener('click', function(e) {
					if (!suggestionContainer.contains(e.target) && e.target !== searchInput) {
						suggestionContainer.classList.add('hidden');
					}
				});

				// 结果项点击事件
				document.getElementById('result-list').addEventListener('click', function(e) {
					const resultItem = e.target.closest('.amap-sug-result');
					if (resultItem) {
						const lnglat = resultItem.getAttribute('data-lnglat');
						if (lnglat) {
							const [lng, lat] = lnglat.split(',').map(Number);
							map.setCenter([lng, lat]);
							map.setZoom(15);

							if (window.innerWidth < 768) {
								toggleResultPanel();
							}
						}
					}
				});
			}

			// 切换结果面板显示/隐藏
			function toggleResultPanel() {
				const resultPanel = document.getElementById('result-panel');
				const toggleResultBtn = document.getElementById('toggle-result');

				isResultVisible = !isResultVisible;

				if (isResultVisible) {
					resultPanel.classList.remove('translate-y-full');
					toggleResultBtn.innerHTML = '<i class="fa fa-times"></i>';
				} else {
					resultPanel.classList.add('translate-y-full');
					toggleResultBtn.innerHTML = '<i class="fa fa-list"></i>';
				}
			}

			// 根据关键词搜索POI
			function searchByKeyword(keyword) {
				clearAllMarkers(); // 搜索前先清除已有标记

				placeSearch.search(keyword, function(status, result) {
					const resultPanel = document.getElementById('result-panel');
					const toggleResultBtn = document.getElementById('toggle-result');

					if (status === 'complete' && result.poiList && result.poiList.pois.length > 0) {
						toggleResultBtn.classList.remove('hidden');

						if (window.innerWidth < 768 && !isResultVisible) {
							toggleResultPanel();
						}

						result.poiList.pois.forEach((poi, index) => {
							const marker = new AMap.Marker({
								position: [poi.location.lng, poi.location.lat],
								title: poi.name,
								content: `<div class="custom-marker w-6 h-6 text-blue-600">${index + 1}</div>`,
								anchor: 'center'
							});

							const infoWindow = new AMap.InfoWindow({
								content: `<div style="padding:10px;">
									<h3 style="margin:0 0 5px 0;">${poi.name}</h3>
									<p style="margin:0; font-size:12px; color:#666;">${poi.address}</p>
								</div>`,
								offset: new AMap.Pixel(0, -30)
							});

							marker.on('click', function() {
								infoWindow.open(map, marker.getPosition());
							});

							marker.setMap(map);
							markers.push({
								marker,
								infoWindow
							});

							const resultItems = document.querySelectorAll('#result-list .amap-sug-result');
							if (resultItems[index]) {
								resultItems[index].setAttribute('data-lnglat',
									`${poi.location.lng},${poi.location.lat}`);
							}
						});

						map.setFitView(markers.map(item => item.marker));
					} else {
						document.getElementById('result-list').innerHTML =
							'<div class="text-center py-4 text-gray-500">未找到相关结果</div>';
						toggleResultBtn.classList.remove('hidden');

						if (window.innerWidth < 768 && !isResultVisible) {
							toggleResultPanel();
						}
					}
				});
			}

			// 增强版清除所有标记函数
			function clearAllMarkers() {
				// 清除搜索结果标记
				markers.forEach(item => {
					if (item.marker && item.marker.remove) {
						item.marker.remove();
					}
					if (item.infoWindow && item.infoWindow.close) {
						item.infoWindow.close();
					}
				});
				markers = [];

				// 清除城市悬停标记的标签（但保留标记本身）
				if (hoverMarker && hoverMarker.setLabel) {
					hoverMarker.setLabel({
						content: ''
					});
				}

				// 清除地图上可能存在的其他标记
				if (map && map.getAllOverlays) {
					const overlays = map.getAllOverlays('marker');
					overlays.forEach(overlay => {
						// 保留城市悬停标记，清除其他所有标记
						if (overlay !== hoverMarker && overlay.remove) {
							overlay.remove();
						}
					});
					hailiang()
				}
			}

			// 获取url中携带的参数
			function getQueryVariable() {
				// 获取当前页面的 URL
				var url = window.location.href;
				const paramsRegex = /[?&]+([^=&]+)=([^&]*)/gi;
				const params = {};
				let match;
				while (match = paramsRegex.exec(url)) {
					params[match[1]] = match[2];
				}
				return params;
			}
		</script>
	</body>
</html>